package net.crowdloud.shared.engine;

import java.util.ArrayList;
import java.util.List;

import net.crowdloud.shared.entities.Problem;
import net.crowdloud.shared.entities.Solution;
import net.crowdloud.shared.entities.Tags;
import net.crowdloud.shared.entities.User;

public class CrowdLoudTagsEngine {

	public static List<Tags> getTagsList(List<User> allUsers, String tags) {

		String[] tagsArray = tags.split(",");

		List<Tags> tagsList = new ArrayList<Tags>();

		for (String tagString : tagsArray) {

			Tags tag = new Tags();

			tag.setTagName(tagString);

			List<User> usersCustomers = new ArrayList<User>();

			List<User> usersProviders = new ArrayList<User>();

			for (User user : allUsers) {

				if (getUsersCostumers(user, tagString)) {

					usersCustomers.add(user);
				}

				if (getUsersProviders(user, tagString)) {

					usersProviders.add(user);
				}
			}

			tag.setUserCustomers(usersCustomers);

			tag.setUserProviders(usersProviders);

			tagsList.add(tag);
		}

		return tagsList;
	}

	private static boolean getUsersCostumers(User user, String tagString) {

		boolean foundCustomer = false;

		for (Problem customerProblem : user.getUserProblems()) {

			if (customerProblem.getTags() != null) {

				for (String customerProblemTag : customerProblem.getTags()
						.split(",")) {

					if (tagString.equals(customerProblemTag)) {

						foundCustomer = true;

						break;
					}

					if (foundCustomer) {

						break;
					}
				}

				if (foundCustomer) {

					break;
				}
			}
		}

		return foundCustomer;
	}

	private static boolean getUsersProviders(User user, String tagString) {

		boolean foundProvider = false;

		for (Solution customerSolution : user.getUserSolutions()) {

			if (customerSolution.getTags() != null) {

				for (String customerSolutionTag : customerSolution.getTags()
						.split(",")) {

					if (tagString.equals(customerSolutionTag)) {

						foundProvider = true;

						break;
					}

					if (foundProvider) {

						break;
					}
				}

				if (foundProvider) {

					break;
				}
			}
		}

		return foundProvider;
	}
}
